# -*- coding: utf-8 -*-
# filename: menu.py
import json, urllib2, time
import urllib
from basic import Basic
from flask import current_app, session
from codingabc.response import ResponseJson
resjson = ResponseJson()

class SendTemplateMsg(object):
    def __init__(self):
        self.appid  = current_app.config['WEIXIN_APPID']
        self.secret = current_app.config['WEIXIN_SECRET']
        self.current_time = int(time.time())

    def get_access_token(self):

        postUrl = ("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" % (self.appid, self.secret))
        urlResp = urllib.urlopen(postUrl)
        urlResp = json.loads(urlResp.read())

        accessToken = urlResp['access_token']
        session['left_time'] = self.current_time + urlResp['expires_in']
        session['accessToken'] = accessToken

        return accessToken

    def api_set_industry(self, industry_id1, industry_id2, accessToken):
        """设置所属行业"""

        if not industry_id1 and not industry_id2:
          return resjson.print_json(11, u'请传入设置所属行业参数')

        postData =u"""{
              "industry_id1":"%s",
              "industry_id2":"%s"
           }"""%(industry_id1, industry_id2)

        postUrl = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=%s" % accessToken

        if isinstance(postData, unicode):
            postData = postData.encode('utf-8')
        res = urllib2.urlopen(postUrl, postData).read()
        set_info = json.loads(res)
        print set_info
        return resjson.print_json(0, u'ok', set_info)

    def get_industry(self, accessToken):
        """获取设置的行业信息"""

        postUrl = "https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=%s" % accessToken
        res = urllib2.urlopen(postUrl).read()
        industry_info = json.loads(res)
        print industry_info
        return industry_info

    def api_add_template(self, accessToken):
        """获得模板ID"""

        postUrl = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=%s" % accessToken
        postData = u"""{
               "template_id_short":"TM00015"
           }"""
        if isinstance(postData, unicode):
            postData = postData.encode('utf-8')
        res = urllib2.urlopen(postUrl, postData).read()
        template_id = json.loads(res)
        print template_id
        return template_id

    def get_all_private_template(self, accessToken):
        """获取模板列表"""

        postUrl = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=%s" % accessToken
        res = urllib2.urlopen(postUrl).read()
        all_private_template = json.loads(res)
        print all_private_template
        return all_private_template

    def del_private_template(self,template_id, accessToken):
        """删除模板"""

        postData = u"""{
                       "template_id":"%s"
                       }"""% template_id
        postUrl = "https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token=%s" % accessToken
        if isinstance(postData, unicode):
            postData = postData.encode('utf-8')
        res = urllib2.urlopen(postUrl, postData).read()
        del_info = json.loads(res)
        print del_info
        return del_info

    def send(self, postData, accessToken):
        """发送模板消息"""

        postUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s" % accessToken
        if isinstance(postData, unicode):
            postData = postData.encode('utf-8')
        res = urllib2.urlopen(postUrl, postData).read()
        send_info = json.loads(res)
        print send_info
        return send_info

if __name__ == '__main__':
    send_temp_msg = SendTemplateMsg()
    openid   = 'o0uant9CxqYGGXdRyDlmh676sKSQ'
    postJson = """
      {
           "touser":"%s",
           "template_id":"%s",
           "url":"http://wap.sz-ruihe.com/notice/new_notice",
           "data":{
                   "first": {
                       "value":"恭喜你购买成功！",
                       "color":"#173177"
                   },
                   "keynote1":{
                       "value":"巧克力",
                       "color":"#173177"
                   },
                   "keynote2": {
                       "value":"39.8元",
                       "color":"#173177"
                   },
                   "keynote3": {
                       "value":"2014年9月22日",
                       "color":"#173177"
                   },
                   "remark":{
                       "value":"欢迎再次购买！",
                       "color":"#173177"
                   }
           }
       }
        """%(openid, 'GQsBP1G5Q4mVuY6NtVNA38etUAsNEi1zLGaSnvXSw34')
    # accessToken = Basic().get_access_token()
    # myMenu.delete(accessToken)
    accessToken='u1l5W28HDzyDolDobUp7tjm5uTkAFKgKaPMT0lfFFfyNcbsJGvSZtAOUYgImbx6gMC3PAMy1-7zoYcNffwVrQU0n2qx3NQsEHwBU1NKFM6Q8B0As7kb7Eu22MtlhpIqPGFPiAJAPOY'
    send_temp_msg.get_all_private_template(accessToken)
    send_temp_msg.del_private_template('7B7Yj7Bw64sfD0PvkARejWl2xaYgUCbKo1inD8Hf1-8',accessToken)
    # send_temp_msg.send(postJson, accessToken)
